<template>
  <div>
    <el-card shadow="never" class="topcard">
      <el-form ref="carForm" :model="pageData">
        <el-row>
          <el-col :span="8">
            <el-form-item label="车辆类型：" label-width="100px">
              <el-select v-model="pageData.truckTypeId" placeholder="请输入">
                <el-option v-for="item in carTypeList" :key="item.id" :label="item.name" :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="车牌号码：" label-width="100px">
              <el-input v-model="pageData.licensePlate" placeholder="请输入车牌号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8" style="padding-left: 20px">
            <el-button type="primary" @click="getTable()">搜索</el-button>
            <el-button @click="reset">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <el-card class="tab-item" shadow="never" style="margin-top: 20px;">
      <el-button type="text" @click="getTable()">全部{{ Deactivation + Available }}</el-button>
      <el-button type="text" @click="getTable(1)">可用{{ Deactivation }}</el-button>
      <el-button type="text" @click="getTable(0)">停用{{ Available }}</el-button>
    </el-card>
    <el-card shadow="never" style="margin-top: 20px;">
      <el-button type="primary" @click="showDialogForm=true">新增车辆</el-button>
      <el-table :data="tableData" :stripe="true" style="width: 100%;border: 1px solid #eee;margin-top: 20px">
        <el-table-column type="index" label="序号"></el-table-column>
        <el-table-column prop="licensePlate" label="车牌号码" width="180"></el-table-column>
        <el-table-column prop="truckTypeName" label="车辆类型" width="120"></el-table-column>
        <el-table-column prop="driverNum" label="司机数量" width="120"></el-table-column>
        <el-table-column label="车辆状态">
          <template #default="{row}">
            <MyStatus :status="row.workStatus" :text="['停用','可用']"></MyStatus>
          </template>
        </el-table-column>
        <el-table-column prop="deviceGpsId" label="GPS设备ID"></el-table-column>
        <el-table-column prop="allowableLoad" label="实载重量（T）"></el-table-column>
        <el-table-column prop="allowableVolume" label="实载体积（方) "></el-table-column>
        <el-table-column label="操作" fixed="right" width="220">
          <template #default="{row}">
            <!--                        {{row}}-->
            <el-row>
              <el-button
                type="text"
                size="mini"
                style="color: #62A7F1"
                @click="$router.push(`/transit/vehicle-detail/?id=${row.id}&formUrlName=车辆管理`)">
                查看详情
              </el-button>
              <span style="color: #eee;margin:0 10px">|</span>
              <el-button
                type="text"
                size="mini"
                :style="row.workStatus?'color: #F56C6C;':'color: #62A7F1;'"
                @click="handleChange(row)">
                {{ row.workStatus == 1 ? '停用' : '启用' }}
              </el-button>
              <span style="color: #eee;margin:0 10px">|</span>
              <el-button
                type="text"
                size="mini"
                style="color: #62A7F1"
                @click="configureDriver(row)">
                配置司机
              </el-button>
            </el-row>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageData.page"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="pageData.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        style="padding: 20px;">
      </el-pagination>
    </el-card>
    <MyDialog
      :show-dialog-form.sync="showDialogForm"
      title="新增车辆"
      @closeD="DialogClose"
      @submit="submit">
      <template #form>
        <el-form ref="formData" :model="formData" :rules="rules">
          <el-form-item label="车辆类型：" label-width="120px" prop="truckTypeId">
            <el-select v-model="formData.truckTypeId" placeholder="请选择">
              <el-option v-for="item in carTypeList" :key="item.id" :label="item.name" :value="item.id"/>
            </el-select>
          </el-form-item>
          <el-form-item label="车牌号码：" label-width="120px" prop="licensePlate">
            <el-input v-model="formData.licensePlate" placeholder="请输入车牌号"></el-input>
          </el-form-item>
          <el-form-item label="GPS设备ID：" label-width="120px" prop="deviceGpsId">
            <el-input v-model="formData.deviceGpsId" placeholder="请输入GPS设备ID"></el-input>
          </el-form-item>
        </el-form>
      </template>
    </MyDialog>
  </div>
</template>

<script>
import { addVehicle, deactivateTheVehicle, enableVehicle, getCarInfo, getCarStatus } from '@/api/truck'
import { getCarsimpleList } from '@/api/truckType'

export default {
  name: 'vehicle-page',
  data () {
    return {
      tableData: [],
      total: 0,
      showDialogForm: false,
      carTypeList: [],
      pageData: {
        page: 1,
        pageSize: 10,
        licensePlate: '',
        workStatus: '',
        truckTypeId: ''
      },
      Available: 0,
      Deactivation: 0,
      formData: {
        licensePlate: '',
        truckTypeId: '',
        deviceGpsId: ''
      },
      rules: {
        truckTypeId: [
          {
            required: true,
            message: '请选择车辆类型',
            trigger: 'blur'
          }
        ],
        licensePlate: [
          {
            required: true,
            message: '请输入车牌号',
            trigger: 'blur'
          },
          {
            pattern: /^([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[a-zA-Z](([DF]((?![IO])[a-zA-Z0-9](?![IO]))[0-9]{4})|([0-9]{5}[DF]))|[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1})$/,
            message: '请输入正确格式的车牌号',
            trigger: 'blur'
          }
        ],
        deviceGpsId: [
          {
            required: true,
            message: '请输入GPS设备ID',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  async created () {
    await this.getTable()
    await this.getCarType()
    await this.getCarStatus()
  },
  methods: {
    // 获取车辆信息列表
    async getTable (num) {
      this.pageData.workStatus = num
      const { data } = await getCarInfo(this.pageData)
      // console.log(data)
      this.total = +data.counts
      this.tableData = data.items
    },
    handleSizeChange (pageSize) {
      this.pageData.pageSize = pageSize
      this.getTable()
    },
    handleCurrentChange (currentPage) {
      this.pageData.page = currentPage
      this.getTable()
    },
    // 获取车辆类型信息列表，下拉框用
    async getCarType () {
      const { data } = await getCarsimpleList()
      this.carTypeList = data
      // console.log(this.carTypeList)
    },
    // 统计车辆状态数量
    async getCarStatus () {
      const { data } = await getCarStatus()
      // console.log(data)
      this.Available = +data['1']
      // console.log(this.Available)
      this.Deactivation = +data['0']
    },
    // 重置
    reset () {
      this.$refs.carForm.resetFields()
    },
    // 弹框
    DialogClose () {
      this.showDialogForm = false
      this.$refs.formData.resetFields()
    },
    // 弹框新增车辆
    submit () {
      this.$refs.formData.validate(async valid => {
        if (valid) {
          await addVehicle(this.formData)
          this.showDialogForm = false
          this.$refs.formData.resetFields()
          await this.getTable()
        }
      })
    },
    // MessageBox 弹框 启用/停用
    async handleChange (row) {
      const h = this.$createElement
      this.$msgbox({
        title: row.workStatus ? '车辆停用' : '车辆启用',
        message: h('p', null, [
          h('p', null, '确定要启用吗？车辆启用需满足以下条件:'),
          h('div', { style: 'display: flex;' }, [
            h('span', { style: 'flex:1' }, '① 车辆信息已完善'),
            h('span', { style: 'flex:1' }, '② 绑定司机>=2,且有排班')
          ])
        ]),
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(async () => {
        if (row.workStatus) {
          await deactivateTheVehicle(row.id)
        } else {
          await enableVehicle(row.id)
        }
        this.getTable()
      }).catch(() => {
        this.getTable()
      })
    },
    // 配置司机
    configureDriver (row) {
      const h = this.$createElement
      this.$msgbox({
        title: '车辆配置',
        message: h('p', null, [
          h('p', null, '确定要启用吗？车辆启用需满足以下条件:'),
          h('div', { style: 'display: flex;' }, [
            h('span', { style: 'flex:1' }, '① 已车辆信息已完善'),
            h('span', { style: 'flex:1' }, '② 车辆无未完成运输任务')
          ])
        ]),
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(async () => {
        this.$router.push({
          path: '/vehicle/driver',
          query: {
            id: row.id
          }
        })
      }).catch(() => {
        this.getTable()
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.topcard {
  .el-form-item {
    margin-bottom: 0;
  }
}

.tab-item {
  margin-top: 20px;

  ::v-deep .el-card__body {
    padding: 0;
  }
}
</style>
